<template>
    <div>
        <div class="container">
            <div class="handle-box">
                <el-input v-model="query.name" placeholder="关键字检索" class="handle-input mr10"></el-input>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
				<el-button type="primary"  @click="handleAdd">添加角色</el-button>
            </div>
            <el-table
                :data="tableData"
                border
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
            >
                <el-table-column prop="id" label="ID" width="55" ></el-table-column>
                <el-table-column prop="name" label="角色名称"></el-table-column>
                <el-table-column prop="created_at" label="创建时间" align="center"></el-table-column>
                <el-table-column prop="updated_at" label="最近更新时间" align="center"></el-table-column>
                <el-table-column label="操作" width="180" >
                    <template slot-scope="scope">
						<el-button v-if="scope.row.id !=1"
						    type="text"
						    icon="el-icon-s-promotion"
						    @click="handleAuth(scope.$index, scope.row)"
						>授权</el-button>
                        <el-button
                            type="text"
                            icon="el-icon-edit"
                            @click="handleEdit(scope.$index, scope.row)"
                        >编辑</el-button>
                        <el-button v-if="scope.row.id !=1"
                            type="text"
                            icon="el-icon-delete"
                            class="red"
                            @click="handleDelete(scope.$index, scope.row)"
                        >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                    background
                    layout="total, prev, pager, next"
                    :current-page="query.pageIndex"
                    :page-size="query.pageSize"
                    :total="pageTotal"
                    @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>
        <!-- 编辑弹出框 -->
         <el-dialog :title="`${currentId?'修改':'新增'}角色`" :visible.sync="showAdd" width="500px">
			<el-form :mode="form" label-position="left" ref="forms" label-width="120px">
				<el-form-item label="标题">
					<el-input style="width: 220px;" placeholder="请输入角色名称" v-model="form.name"></el-input>
				</el-form-item>
				<el-form-item>
					<div class="btn-contnet">
						<el-button v-if="currentId" type="primary" :loading="creating" @click="editSure">保存
						</el-button>
						<el-button v-else type="primary" :loading="creating" @click="addSure">确认</el-button>
						<el-button v-if="currentId" @click="showAdd=false">取消</el-button>
					</div>
				</el-form-item>
			</el-form>
		</el-dialog>
		
		<!-- 授权弹出框 -->
		<el-dialog title="选择权限" :visible.sync="showAuth">
			<el-tree :data="authList"
					 v-if="showAuth"
					 show-checkbox
					 :check-strictly="true"
					 default-expand-all
					 node-key="id"
					 ref="tree"
					 :props="authProps"
					 :default-checked-keys="checkedKeys"
					 highlight-current></el-tree>
			<div class="btn-contnet">
				<el-button type="primary" :loading="creating" @click="authPromises">赋予权限</el-button>
				<el-button @click="showAuth=false">取消</el-button>
			</div>
		 </el-dialog>
    </div>
</template>

<script>
import {getRoleList,roleAdd,roleEdit,roleDel,nodeAllList,authForUser} from '../../api/auth.js';

export default {
    data() {
        return {
			loading: false,
			creating: false,
            query: {
                name: '',
                page: 1,
                pageSize: 10
            },
			pageTotal: 0,
            tableData: [],
            multipleSelection: [],
            delList: [],
			showAdd: false,//添加弹窗
			currentId: 0, //当前id
			currentRow:{},
			form: {name:'',},
			showAuth: false, //授权弹窗
			authList:[],//授权数据
			authProps: {
				children: 'children',
				label: 'title'
			},
			checkedKeys: [], //已授权节点
        };
    },
    created() {
        this.getData();
    },
    methods: {
        // 获取 easy-mock 的模拟数据
        async getData() {
            let [e, data] = await getRoleList(this.query)
            if (e instanceof Error) throw e;
            this.tableData = data.data.list
        },
		//获取授权数据
		getAuthList () {
			nodeAllList().then( res => {
				let [e,data] = res
				this.authList = data.data
			})
		},
		//添加btn
		handleAdd(){
			this.currentId = 0
			this.form.name = ''
			this.showAdd = true
		},
		//确认添加按钮
		addSure(){
			roleAdd(this.form).then( res => {
				this.showAdd = false
				this.getData()
			})
		},
		// 编辑操作
		handleEdit(index, row) {
			this.currentId = row.id
			this.form.name = row.name
			this.showAdd = true
		},
		// 保存编辑
		editSure() {
			roleEdit({
				id :this.currentId,
				name: this.form.name
			}).then( res => {
				this.showAdd = false
				this.$message.success(`修改成功`);
				this.getData()
			})
		},
        // 触发搜索按钮
        handleSearch() {
            this.getData();
        },
        // 删除操作
        handleDelete(index, row) {
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            }).then(() => {
				roleDel({id:row.id}).then( res => {
					this.$message.success('删除成功');
					this.tableData.splice(index, 1);
				})
            }).catch(() => {});
        },
        // 分页导航
        handlePageChange(val) {
            this.$set(this.query, 'page', val);
            this.getData();
        },
		//授权弹窗触发
		handleAuth(index,row){
			this.currentRow = row
			this.checkedKeys = row.nodes;
			if (this.authList.length) {
				this.showAuth = true
			} else {
				this.getAuthList()
				setTimeout( ()=> {
					this.showAuth = true
				},300)
			}
		},
		//确认授权
		authPromises(){
			let Nodes = this.$refs.tree.getCheckedNodes(false, true);
			let node_id = Nodes.reduce((ary,item,index)=>{
			   ary.push(item.id);
			   return ary
			},[]);
			this.creating = true;
			authForUser({
				role_id: this.currentRow.id,
				node_id
			}).then( ([e,data]) => {
				this.creating = false;
				if (!e) {
					this.$message.success('授权成功');
					this.showAuth = false;
					this.getData();
				}
			})
		}
    },
};
</script>

<style scoped>

</style>
